<?php
/**
 * 下单页面相关
 * User: lyz
 * Date: 2016/2/28
 * Time: 10:39
 */
namespace Api\Controller;

use Think\Controller;
use Api\Model\LoginModel;
use Api\Model\RepairOrderModel;

/**
 *下单接口
 */
class OrderController extends BaseController
{


    public function test()
    {
        file_put_contents("/tmp/sql.txt", "这是什么呢");
        file_put_contents("/tmp/sql.txt", "222222");
        exit;
        $jpushObj = new \Org\Util\JPush_test();
        $receive = 'all';//别名
        $content = '建刚！！！！！！？';
        $m_type = 'tb';
        $m_txt = '';
        $m_time = '600';        //离线保留时间
        $res = $jpushObj->send_pub($receive, $content, '', $m_txt, $m_time);
        var_dump($res);
    }

    /**
     * 下单首页页面[下单首页接口]
     * @param  string $user_name
     * @param  string $key
     * @param  string $rid 当前登录角色类型
     * @param  int $cid 当前选择的一级分类
     * @return array
     * @author lyz
     */
    public function index()
    {
        $user = M('user');
        $map['phone'] = I('post.phone', '');
        $userInfo = $user->where($map)->find();
        $errorInfo = array();
        $dataInfo = array();
        $dataInfo['code'] = 200;
        $dataInfo['address'] = array();//地址信息
        $dataInfo['address'] = '';//先定义常用地址为false
        $dataInfo['category'] = array();//二级分类信息
        #查询用户的地址[常用地址,如果非 常用地址则把地址列表丢出去让前端做处理]
        #查询丢过来的一级分类下的二级分类
        $phone = I('post.phone', '');//用户名
        $key = I('post.key', '', 'special_chars');//用户名
        $rid = I('post.rid/d', '');//当前登录用户的登录角色
        $cid = I('post.cid/d', '');//当前登录用户选择的一级分类
        $checkInfo = checkRole($phone, $key, $rid, false);//检测当前登录用户是否有操作权限
        if ($checkInfo['code'] != 200) {
            $this->ajaxReturn($checkInfo, 'JSON');
        }
        if ($cid == 0) {
            $errorInfo['code'] = '2002';
            $errorInfo['msg'] = '请选择二级分类';
            $this->ajaxReturn($errorInfo, 'JSON');
        }
        $addressMap = array();
        $addressMap['user_id'] = $userInfo['user_id'];
        $addressMap['status'] = 1;
        $addressMap['is_del'] = 0;
        $addressInfo = M('address')->where($addressMap)->find();
        if (!empty($addressInfo)) {
            $dataInfo['address']['isCommon'] = true;
            $dataInfo['address']['addr_id'] = $addressInfo['id'];//联系人
            $dataInfo['address']['contacts'] = $addressInfo['contacts'];//联系人
            $dataInfo['address']['address'] = $addressInfo['address'];//地址
            $dataInfo['address']['doorplate'] = $addressInfo['doorplate'];//门牌号
            $dataInfo['address']['phone'] = $addressInfo['phone'];//电话号码
            $dataInfo['address']['lng'] = $addressInfo['lng'];//经度
            $dataInfo['address']['lat'] = $addressInfo['lat'];//纬度
        }
        /////////////////////////选择类型信息
        $categoryMap = array();
        // $categoryMap['type'] = 1;
        $categoryMap['status'] = 1;//可用状态
        $categoryMap['pid'] = array("EQ", $cid);//二级分类
        //dia_standard_cost 标准诊断费
        //dia_expert_cost 专修诊断费
        //dia_wind_cost 顺风诊断费
        $categoryListInfo = M('category')->field('dia_standard_cost,dia_expert_cost,dia_wind_cost,category_id,icon,category_name,desc,order')->where($categoryMap)->order(array('order' => 'desc'))->select();
        if (!empty($categoryListInfo)) {
            //$categoryListInfo[0]['isSelect']=true;
            $dataInfo['category'] = array_chunk($categoryListInfo, 4);
        } else {
            $errorInfo['code'] = '2001';
            $errorInfo['msg'] = '该分类下没有子分类';
            $this->ajaxReturn($errorInfo, 'JSON');
        }
        $this->ajaxReturn($dataInfo, 'JSON');
    }

    private function _getTypeName($type)
    {
        $arr = array(
            1 => '顺风',
            2 => '标准',
            3 => '专修',
        );
        return $arr[$type];
    }

    /**
     *下单页面[下一步]
     * @param  string $user_name
     * @param  string $key
     * @param  string $rid 当前登录角色类型
     * @param  int $cid 当前选择的一级分类
     * @param  string $faultIds 故障id列表逗号分隔
     * @param  int $type 服务方式 顺风/标准/专修
     */
    public function orderNext()
    {
        $data = array();
        $phone = I('post.phone', '', 'special_chars');//用户名
        $key = I('post.key', '', 'special_chars');//用户名
        $rid = I('post.rid/d', '');//当前登录用户的登录角色
        $cid = I('post.cid/d', '');//当前登录用户选择的一级分类
        $type = I('post.type/d', '');//服务方式[顺风，标准，专修]
        $faultIds = I('post.faultIds', '', 'special_chars');//故障id列表
        $volume_id = I('post.volume_id/d', '');//电子券id
        $checkInfo = checkRole($phone, $key, $rid, false);//检测当前登录用户是否有操作权限
        //比对故障是否一致
        $checkFaultInfo = $this->checkFaultCnt($faultIds);
        if ($checkFaultInfo['code'] != 200) {
            $this->ajaxReturn($checkFaultInfo, 'JSON');
        }
        //比对故障是否一致
        if ($checkInfo['code'] != 200) {
            $this->ajaxReturn($checkInfo, 'JSON');
        }
        if ($cid == 0) {
            $errorInfo['code'] = '2002';
            $errorInfo['msg'] = '请选择二级分类';
            $this->ajaxReturn($errorInfo, 'JSON');
        }
        $categoryObj = M('category');
        $categoryMap['category_id'] = $cid;
        $categoryInfo = $categoryObj->field("category_id")->where($categoryMap)->find();
        if (empty($categoryInfo)) {
            $errorInfo['code'] = '2004';
            $errorInfo['msg'] = '该分类不存在,请重新选择';
            $this->ajaxReturn($errorInfo, 'JSON');
        }
        $faultMap = array();
        //$faultMap['category_id'] = array('in', $cid);//cid需要验证
        $faultMap['fault_id'] = array('in', $faultIds);//cid需要验证
        //$faultMap['type'] = $type;//服务状态
        $faultCostObj = M('fault_cost');
        $faultObj = M('fault');
        $faultList = array();
        $faultList = $faultObj->field('fault_id,name,category_id,fault_type,order')->where($faultMap)->select();//先找对应的故障
        $costData = array();
        $costTotal = 0;//总花费
        if (!empty($faultList)) {
            foreach ($faultList as $key => $val) {
                //查询故障对应的服务方式的价格
                $FaultConstData = $faultCostObj->field('fault_id,type,material_cost,deplete_cost,artificial_cost')->where(array('fault_id' => $val['fault_id']))->select();
                if (!empty($FaultConstData)) {
                    foreach ($FaultConstData as $kk => $vv) {
                        if ($vv['type'] == $type) {
                            $vv['type_name'] = $this->_getTypeName($type);
                            $name = $faultObj->field('name')->find($vv['fault_id']);
                            $vv['name'] = $name['name'];
                            $vv['costTotal'] = bcadd($vv['material_cost'], $vv['deplete_cost'], 2);
                            $vv['costTotal'] = bcadd($vv['costTotal'], $vv['artificial_cost'], 2);
                            $costTotal = bcadd($costTotal, $vv['costTotal'], 2);
                            $faultList[$key]['cost'] = $vv;
                            // $faultList[$key]['cost']['type_name'] = $vv;
                        }
                    }
                } else {
                    $faultList[$key]['cost'] = null;
                }
            }
        }

        $fieldType = '';
        switch ($type) {//选择服务诊断费类型
            case 1://顺风
                // $categoryMap['type_name'] = '顺风';
                $fieldType = 'dia_wind_cost as cost';
                break;
            case 2://标准
                //  $categoryMap['type_name'] = '标准';
                $fieldType = 'dia_standard_cost as cost';
                break;
            case 3://专修
                //$categoryMap['type_name'] = '专修';
                $fieldType = 'dia_expert_cost as cost';
                break;
        }
        $categoryMap['category_id'] = $cid;
        $categoryData = $categoryObj->field("$fieldType,category_id,category_name")->where($categoryMap)->find();
        $categoryData['type_name'] = $this->_getTypeName($type);
        $data['categoryCost'] = $categoryData;
        $data['itemCost'] = $costTotal;
        $data['itemCostTotal'] = bcadd($costTotal, $categoryData['cost'], 2);
        //电子券
        if (!empty($volume_id)) {
            $user = M('user');
            $map['phone'] = $phone;
            $userInfo = $user->where($map)->find();
            $volume = M('VolumeList');
            $volumeMap = array();
            $volumeMap['user_id'] = $userInfo['user_id'];
            $volumeMap['status'] = 1;
            //start_time>=2016-4-27 and end_time <=2016-4-29
            $volumeMap['volume_list_id'] = $volume_id;
            $volumeMap['start_time'] = array('elt', time());
            $volumeMap['end_time'] = array('egt', time());
            $volumeList = $volume->field('volume_name,total,type,min,category')->where($volumeMap)->find();
            if (empty($volumeList)) {
                //无效的电子券//找不到状态为1的电子券
                $errorInfo['code'] = '2003';
                $errorInfo['msg'] = '无效的电子券,请重新选择电子券';
                $this->ajaxReturn($errorInfo, 'JSON');
            }
            $categoryList = explode('|', $volumeList['category']);
            if (!in_array($cid, $categoryList)) {
                $errorInfo['code'] = '2004';
                $errorInfo['msg'] = '该电子券无法在该分类下使用,请重新选择电子券';
                $this->ajaxReturn($errorInfo, 'JSON');
            }
            if ($data['itemCostTotal'] < $volumeList['min']) {
                $errorInfo['code'] = '2005';
                $errorInfo['msg'] = '该电子券未到指定使用金额，请重新选择';
                $this->ajaxReturn($errorInfo, 'JSON');
            }
            if (bcdiv($volumeList['total'], $data['itemCostTotal'], 2) > 0.5) {//电子券使用不能超过总金额的50%
                $errorInfo['code'] = '2006';
                $errorInfo['msg'] = '电子券使用不能超过总金额的50%';
                $this->ajaxReturn($errorInfo, 'JSON');
            }
            $data['itemCostTotal'] = bcsub($data['itemCostTotal'], $volumeList['total'], 2);
            $data['volumeCostTotal'] = $volumeList['total'];
            $data['volumeData'] = $volumeList;
        }
        $data['cost'] = $faultList;
        $this->ajaxReturn($data, 'JSON');
    }

    /**
     * 下单页面[点击下单页面]
     * @param  string $user_name
     * @param  string $key
     * @param  string $rid 当前登录角色类型
     * @param  int $cid 分类类型
     * @param  string $faultIds 维修项目id列表
     * @param  int $type 服务方式[顺风，标准,专修]
     * @param  string $tel 收货人电话
     * @param  string $name 收货人姓名
     * @param  string $bookTime 预约时间[指派下单的时候才存在]预约时间1
     * @param  string $addr 收货人地址1
     * @param  string $orderType 下单类型[即时下单，预约下单]
     * @return array
     * @author lyz
     */

    public function order()
    {
        //file_put_contents("/tmp/loggo.txt",'order--------go',FILE_APPEND);
        $return = array();
        $data = array();
        $phone = I('post.phone', '', '/^1[3-9][0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/');//用户名
        $key = I('post.key', '', 'special_chars');//key
        $rid = I('post.rid/d', '');//当前登录用户的登录角色
        $cid = I('post.cid/d', '');//当前登录用户选择的一级分类
        $user_id = I('post.user_id', '');//当前登录用户选择的一级分类
        $faultIds = I('post.faultIds', '', 'special_chars');//故障id列表
        $type = I('post.type/d', '');//服务方式[顺风，标准，专修]
        $address_id = I('post.address_id', '');//地址id
        $tip = I('post.tip', 0, 'intval');
       /* $lng = I('post.lng', '');//经度
        $lat = I('post.lat', '');//经度
        updateLngLat($phone, $lng, $lat);//修改用户经纬度        //lng  经度,lat  纬度*/
        $book_time = I('post.bookTime', '', 'special_chars');//预约时间
        $book_time = strtotime($book_time);
        $order_type = I('post.orderType/d');//订单类型
        $volume_id = I('post.volume_id/d');//电子券id

        $master_phone = I('post.master_phone');//指派师傅号码
        $master_id = I('post.master_id/d');//指派师傅id

        $uswhere['phone']=$phone;
        $us=M('user')->where($uswhere)->find();
        if($us['user_status']==2 || $us['user_status']==1){
            $errorInfo['code'] = '2002';
            $errorInfo['msg'] = '用户目前不能下单';
            $this->ajaxReturn($errorInfo, 'JSON');
        }
        //比对故障是否一致
        $checkFaultInfo = $this->checkFaultCnt($faultIds);

        if ($checkFaultInfo['code'] != 200) {
            $this->ajaxReturn($checkFaultInfo, 'JSON');
        }
        //比对故障是否一致
        $checkInfo = checkRole($phone, $key, $rid, false);//检测当前登录用户是否有操作权限
        //比对故障分类与传入分类是否一致
        $this->_checkCategory($cid, $faultIds);
        $user = M('user');
        $map['phone'] = $phone;
        $userInfo = $user->where($map)->find();
        if ($checkInfo['code'] != 200) {
            $this->ajaxReturn($checkInfo, 'JSON');
        }
        if ($cid == 0) {
            $errorInfo['code'] = '2002';
            $errorInfo['msg'] = '请选择二级分类';
            $this->ajaxReturn($errorInfo, 'JSON');
        }
        $categoryObj = M('category');
        $categoryMap['category_id'] = $cid;
        $categoryInfo = $categoryObj->field("category_id")->where($categoryMap)->find();
        if (empty($categoryInfo)) {
            $errorInfo['code'] = '2004';
            $errorInfo['msg'] = '该分类不存在,请重新选择';
            $this->ajaxReturn($errorInfo, 'JSON');
        }


        //查询用户是否存在5张未完成支付或者未取消的订单
        $is_existWhere['status']=array('not in','-1,8,9,10');
        $is_existWhere['user_id']=$userInfo['user_id'];
        $is_existConut=M('repair_order')->where($is_existWhere)->count();
     /*   if($is_existConut>=5){
            $errorInfo['code'] = '2016';
            $errorInfo['msg'] = '还有未完成订单，请先完成订单再下单';
            $this->ajaxReturn($errorInfo, 'JSON');
        }*/


        //指派师傅
        if (!empty($master_phone) && !empty($master_id)) {
            $masterFlag = $this->checkMaster($master_phone, $master_id, $order_type, $type);
            if (!$masterFlag) {
                //没找到这个师傅。或者师傅模式没设置
                $errorInfo['code'] = '2019';
                $errorInfo['msg'] = '找不到对应的师傅，或者师傅模式没设置';
                $this->ajaxReturn($errorInfo, 'JSON');
            }
        }
        $faultMap = array();
        //$faultMap['category_id'] = array('in', $cid);//cid需要验证
        $faultMap['c.fault_id'] = array('in', $faultIds);//
        $faultMap['type'] = $type;//服务状态
        $faultCostObj = M('fault_cost');
        $prex = C('DB_PREFIX');
        $FaultData = $faultCostObj
            ->field('c.fault_id,s.name,c.type,c.material_cost,c.deplete_cost,c.artificial_cost,s.fault_type')
            ->join(" as  c left JOIN {$prex}fault as s  ON c.fault_id = s.fault_id")
            ->where($faultMap)
            ->select();
        $costData = array();
        $costTotal = 0;//总花费
        if (!empty($FaultData)) {
            foreach ($FaultData as $key => $val) {
                if ($val['type'] == $type) {
                    $val['costTotal'] = bcadd($val['material_cost'], $val['deplete_cost'], 2);
                    $val['costTotal'] = bcadd($val['costTotal'], $val['artificial_cost'], 2);
                    $costTotal = bcadd($costTotal, $val['costTotal'], 2);
                    $costData[] = $val;
                }
            }
        }
        $data['cost'] = $costData;
        $fieldType = '';
        switch ($type) {//选择服务诊断费类型
            case 1://顺风
                $fieldType = 'dia_wind_cost as cost';
                break;
            case 2://标准
                $fieldType = 'dia_standard_cost as cost';
                break;
            case 3://专修
                $fieldType = 'dia_expert_cost as cost';
                break;
        }
        $categoryMap['category_id'] = $cid;
        $categoryData = $categoryObj->field("$fieldType,category_id,category_name")->where($categoryMap)->find();
        /////还有电子卷！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
        if (!empty($volume_id)) {
            $volume = M('VolumeList');
            $volumeMap = array();
            $volumeMap['user_id'] = $userInfo['user_id'];
            $volumeMap['status'] = 1;
            //start_time>=2016-4-27 and end_time <=2016-4-29
            $volumeMap['volume_list_id'] = $volume_id;
            $volumeMap['start_time'] = array('elt', time());
            $volumeMap['end_time'] = array('egt', time());
            $volumeList = $volume->field('volume_name,total,type,min,category,category_id')->where($volumeMap)->find();
            if (empty($volumeList)) {
                //无效的电子券//找不到状态为1的电子券
                $errorInfo['code'] = '2003';
                $errorInfo['msg'] = '无效的电子券,请重新选择电子券';
                $this->ajaxReturn($errorInfo, 'JSON');
            }
            $categoryList = explode('|', $volumeList['category_id']);
            if (!in_array($cid, $categoryList)) {
                $errorInfo['code'] = '2004';
                $errorInfo['msg'] = '该电子券无法在该分类下使用,请重新选择电子券';
                $this->ajaxReturn($errorInfo, 'JSON');
            }
            $data['itemCostTotal'] = I('post.totalPrice', '');
            if ($data['itemCostTotal'] < $volumeList['min']) {
                $errorInfo['code'] = '2005';
                $errorInfo['msg'] = '该电子券未到指定使用金额，请重新选择';
                $this->ajaxReturn($errorInfo, 'JSON');
            }
            if (bcdiv($volumeList['total'], $data['itemCostTotal'], 2) > 0.5) {//电子券使用不能超过总金额的50%
                $errorInfo['code'] = '2006';
                $errorInfo['msg'] = '电子券使用不能超过总金额的50%';
                $this->ajaxReturn($errorInfo, 'JSON');
            }//计算电子券的钱
            $data['itemCostTotal'] = bcsub($data['itemCostTotal'], $volumeList['total'], 2);
            //$data['volumeCostTotal'] =$volumeList['total'];
            //$data['volumeData'] =$volumeList;
        }
        $data['categoryCost'] = $categoryData['cost'];
        $data['itemCostTotal'] = bcadd($costTotal, $categoryData['cost'], 2);
        $ip = get_client_ip();
        $shWhere['user_id'] = $user_id;
        $shWhere['id'] = $address_id;
        $shipping = M('address')->where($shWhere)->find();
        if (empty($shipping)) {
            $return['code'] = 2006;
            $return['msg'] = '收货人信息为空';
            $this->ajaxReturn($return, 'JSON');
            //没选择地址
        }
        $sql="select * from zsf_invite where find_in_set(".$userInfo['user_id'].",share_userid) limit 1";
        $exist_invite=M()->query($sql);
        if($exist_invite){
            $insertMap['invite_master'] =$exist_invite[0]['user_id'];
        }
        $shipping_tel = $shipping['phone'];
        $shipping_name = $shipping['contacts'];
        $shipping_addr = $shipping['address'];
        $shipping_city = $shipping['city'];
        $doorplate = $shipping['doorplate'];
        $insertMap['lat'] =$shipping['lat'] ;
        $insertMap['lng'] =$shipping['lng'] ;
        $repair_order_num_alias = build_order_no();
        $insertMap['repair_order_num_alias'] = $repair_order_num_alias;//对外订单编号
        $insertMap['user_id'] = $userInfo['user_id'];//会员id
        $insertMap['shipping_tel'] = $shipping_tel;//收货人电话
        $insertMap['shipping_name'] = $shipping_name;//收货人姓名
        $insertMap['shipping_addr'] = $shipping_addr;//收货人地址
        $insertMap['doorplate'] = $doorplate;
        $insertMap['city'] = $shipping_city;
        $insertMap['payment_code'] = '';//支付方式[]
        $insertMap['category_id'] = $cid;//分类id
        $insertMap['fault_id_list'] = $faultIds;//故障列表
        $insertMap['fault_type'] = $checkFaultInfo['fault_type'];//[故障类型:标准,非标准]
        $insertMap['mode_charging'] = $type;//[服务方式与个人设置中的付费方式对应][单选][1:顺风,2:标准,3:专修]
        $insertMap['total'] = $data['itemCostTotal'];//支付总额
        $insertMap['ip'] = $ip;//下订单的ip
        $insertMap['pay_time'] = '';//付款时间戳
        $insertMap['volume_list_id'] = $volume_id;//电子卷,多张逗号分隔
        $insertMap['worker_user_id'] = '';//师傅[用户]id
        $insertMap['order_type'] = $order_type;//订单类型[1:即时下单,2预约下单]
        $insertMap['book_time'] = $book_time;//预约时间
        $insertMap['set_time'] = time();
        $insertMap['tip'] = empty($tip)?0:$tip;
        $insertMap['push_cnt'] = '';//推送了多少位师傅
        $insertMap['protocol_id'] = '';//支付协议所用id
        $insertMap['category_name'] = $categoryData['category_name'];
        $insertMap['diagnosis_cost'] = $data['categoryCost'];//诊断费
        if ($masterFlag) {
            $insertMap['worker_user_id'] = $master_id;//指定师傅id
            $insertMap['status'] = 2;//订单状态
        } else {
            $insertMap['status'] = 1;//订单状态
        }
        $order = new RepairOrderModel();
        $RepairOrderDetail = M('RepairOrderDetail');
        $RepairOrderDetail->startTrans();
        $result = $order->add($insertMap);

        //这里推送到符合规则的师傅应该放入redis的队列里面
        if ($result > 0) {

            foreach ($costData as $key => $val) {
                $detailData = array();
                $detailData['fault_type'] = $val['fault_type'];//[故障类型:1标准,2非标准]
                $detailData['repair_order_id'] = $result;//对内订单号
                $detailData['fault_id'] = $val['fault_id'];//对应故障金额
                $detailData['price'] = $val['costTotal'];//对应故障金额
                $detailData['status'] = 0;//状态
                $detailData['add_time'] = time();//时间戳
                $detailData['material_cost'] = $val['material_cost'];//主材钱
                $detailData['deplete_cost'] = $val['deplete_cost'];//耗材钱
                $detailData['artificial_cost'] = $val['artificial_cost'];//人工费
                $detailData['fault_name'] = $val['name'];//故障名
                $resultDetail = $RepairOrderDetail->add($detailData);//插入到订到描述表
            }
            //插入到订单记录表
            if ($masterFlag) {
                $orderStatusRes = $this->addToHistory($result, 2, 0);
            }else{
                $orderStatusRes = $this->addToHistory($result, 1, 0);
            }
            if ($orderStatusRes > 0) {
                $RepairOrderDetail->commit();
                $orderInfo = $order->find($result);
                $redis = S(array('type' => 'redis'));
                $key=C('REPAIR_ORDER') . '_key_' . $result;
                S($key,1,60*60*24*3);
                if (!$masterFlag) {
                    $this->_getResult($result);
                    //$redis = S(array('type' => 'redis'));
                    //$redis->auth(C('DATA_REDIS_AUTH'));
                    //$res = $redis->lpush(C('REPAIR_ORDER_PUSH_KEY'), $result);
                    //file_put_contents("/tmp/log.txt", "REPAIR_ORDER_PUSH_KEY====" . var_export($result . "--" . $res, true) . "\r\n", FILE_APPEND);
                }
                $return['order_id'] = $orderInfo['repair_order_num_alias'];
                $return['addr'] = $orderInfo['shipping_addr'];
                $return['code'] = 200;
                $return['msg'] = '添加成功';
            } else {
                $return['code'] = '2014';
                $return['msg'] = '添加失败';
                $RepairOrderDetail->rollback();
            }
            $this->ajaxReturn($return, 'JSON');
        }
    }

    /**
     * 修改订单故障、增加其它故障、一口价
     */
    public function update_order()
    {
        $return = array();
        $data = array();
//        $phone = I('post.phone', '', '/^1[3-9][0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/');//用户名
//        $key = I('post.key', '', 'special_chars');//key
//        $rid = I('post.rid/d', '');//当前登录用户的登录角色
//        $agreement_id = I('post.agreement_id/d', '');//当前登录用户的登录角色

        $faultIds = I('post.faultIds', '', 'special_chars');//故障id列表
        $order_id = I('post.order_id', '');//订单对外id
        $agreement_id = I('post.agreement_id'); //支付协议id

        $userInfo = M('repair_order')->field('worker_user_id,repair_order_id')->where("repair_order_num_alias = $order_id")->find();
        $material_cost = I('post.material_cost', '');//主材钱
        $deplete_cost = I('post.deplete_cost', '');//耗材钱
        $artificial_cost = I('post.artificial_cost', '');//人工费
        $fault_name = I('post.fault_name', '');//故障名称
        $defineIds = I('post.defineIds','');//自定义故障id
        $fixed_price = I('post.fixed_price',''); //一口价

//        $checkInfo = checkRole($phone, $key, $rid, true);//检测当前登录用户是否有操作权限
//        if ($checkInfo['code'] != 200) {
//            $this->ajaxReturn($checkInfo, 'JSON');
//        }
//        $user = M('user');
//        $userMap = array();
//        $userMap['phone'] = $phone;
//        $userInfo = $user->field('user_id')->where($userMap)->find();

        $RepairOrder = M('RepairOrder');
        $orderMap = array();
        $orderMap['repair_order_num_alias'] = $order_id;
        // $orderMap['status'] = 3;//只有等于3的时候才能修改订单
        $orderInfo = $RepairOrder->field('repair_order_id,worker_user_id,mode_charging,category_id,update_cnt')->where($orderMap)->find();
        if (empty($agreement_id)) {
            $data = array('err_code' => 1002, 'err_msg' => '缺少支付协议id');
            $this->ajaxReturn($data, 'JSON');
        }
        if (empty($orderInfo)) {
            //不存在订单，或者不存在状态为3的订单
            //直接返回
            $return['err_code'] = 2008;
            $return['err_msg'] = '不存在订单，或者不存在状态为3的订单';
            $this->ajaxReturn($return, 'JSON');
        }

//        if (empty($userInfo)) {
//            $return['code'] = 2009;
//            $return['msg'] = '不存在该用户';
//            $this->ajaxReturn($return, 'JSON');
//        }
//        if ($userInfo['user_id'] != $orderInfo['worker_user_id']) {
//            $return['code'] = 2010;
//            $return['msg'] = '您不是该订单的师傅';
//            $this->ajaxReturn($return, 'JSON');
//        }

        //如果订单详情里面被师傅修改，而业主未同意/不同意的情况下不能修改第二次
        $RepairOrderDetail = M('RepairOrderDetail');
        $orderDetailMap = array();
        $orderDetailMap['repair_order_id'] = $orderInfo['repair_order_id'];
        $orderDetailMap['status'] = 1;
        $detaiInfo = $RepairOrderDetail->where($orderDetailMap)->select();
        if (!empty($detaiInfo)) {
            $return['err_code'] = 2011;
            $return['err_msg'] = '业主没确认修改订单，业主确认或者不同意后方可进行修改';
            $this->ajaxReturn($return, 'JSON');
        }
        $update_cnt = $orderInfo['update_cnt'];//订单修改次数
        $type = $orderInfo['mode_charging'];//类型
        $cid = $orderInfo['category_id'];//分类id
        //查找支付协议是否存在
        $agreementObj = M('agreement');
        $agreementMap = array();
        $agreementMap['cid'] = $cid;
        $agreementMap['id'] = $agreement_id;
        $agreementInfo = $agreementObj->where($agreementMap)->find();
        if (empty($agreementInfo)) {
            $return['err_code'] = 2016;
            $return['err_msg'] = '支付协议id不存在';
            $this->ajaxReturn($return, 'JSON');
        }
        $repair_order_id = $orderInfo['repair_order_id'];//订单号
        ######################################
        $faultMap = array();
        $faultMap['c.fault_id'] = array('in', $faultIds);//故障id
        $faultMap['c.type'] = array('eq',$type);
        $faultCostObj = M('fault_cost');
        $prex = C('DB_PREFIX');

        if(!empty($faultIds)) {
            $FaultData = $faultCostObj
                ->field('c.fault_id,s.name,c.type,c.material_cost,c.deplete_cost,c.artificial_cost')
                ->join(" as  c left JOIN {$prex}fault as s  ON c.fault_id = s.fault_id")
                ->where($faultMap)
                ->group("c.fault_id")
                ->select();
        }else{
            $FaultData = array();
        }

        //如果有对故障进行修改就把faultid传过来
//        && !empty($defineIds)

        //用户自定义的故障
        //$material_cost//主材钱
        //$deplete_cost//耗材钱
        //$artificial_cost//人工费
        //$fault_name=//故障名称
        if (!empty($material_cost) && !empty($deplete_cost) && !empty($artificial_cost) && !empty($fault_name)) {
            //全部不为空才插入,并且全部金钱必须大于0才写入
            $fault_name = explode(',',$fault_name);
            $material_cost = explode(',',$material_cost);
            $deplete_cost = explode(',',$deplete_cost);
            $artificial_cost = explode(',',$artificial_cost);
//            $defineIds = explode(',',$defineIds);

            $cost_count = count($fault_name);
            for($i=0;$i<$cost_count;$i++) {
                $newFault = array();
                $newFault['fault_id'] = 0;
                $newFault['name'] = $fault_name[$i];
                $newFault['type'] = $type;
                $newFault['material_cost'] = $material_cost[$i];
                $newFault['deplete_cost'] = $deplete_cost[$i];
                $newFault['artificial_cost'] = $artificial_cost[$i];
                array_push($FaultData, $newFault);

                $defineFault['order_id'] = $order_id;
                $defineFault['fault_name'] = $fault_name[$i];
                $defineFault['material_cost'] = $material_cost[$i];
                $defineFault['deplete_cost'] = $deplete_cost[$i];
                $defineFault['artificial_cost'] = $artificial_cost[$i];
                $defineFault['add_time'] = time();
                M('fault_define')->add($defineFault);
            }
        }

        //用户自定义的故障
        $costData = array();
        $costTotal = 0;//总花费

        if (!empty($FaultData)) {
            foreach ($FaultData as $key => $val) {
                if ($val['type'] == $type) {
                    $val['costTotal'] = bcadd($val['material_cost'], $val['deplete_cost'], 2);
                    $val['costTotal'] = bcadd($val['costTotal'], $val['artificial_cost'], 2);
                    $costTotal = bcadd($costTotal, $val['costTotal'], 2);
                    $costData[] = $val;
                }
            }
        }
        $data['cost'] = $costData;
        $categoryObj = M('category');
        $fieldType = '';
        switch ($type) {//选择服务诊断费类型
            case 1://顺风
                $fieldType = 'dia_wind_cost as cost';
                break;
            case 2://标准
                $fieldType = 'dia_standard_cost as cost';
                break;
            case 3://专修
                $fieldType = 'dia_expert_cost as cost';
                break;
        }
        $categoryMap['category_id'] = $cid;
        $categoryData = $categoryObj->field("$fieldType,category_id")->where($categoryMap)->find();

        if (!empty($categoryData)) {
            $data['categoryCost'] = $categoryData['cost'];
            $data['itemCostTotal'] = $costTotal;
//            $data['itemCostTotal'] = bcadd($costTotal, $categoryData['cost'], 2);
        } else {
            $return['err_code'] = 2016;
            $return['err_msg'] = '分类诊断费不能为空';
            $this->ajaxReturn($return, 'JSON');
            //$data['categoryCost'] = array();
        }

        //这里要修改订单的状态为4[师傅修改订单状态],并且修改次数+1
        $updateOrderInfo = array();
        $RepairOrder->startTrans();//开启事务
        $updateOrderInfo['update_cnt'] = $update_cnt + 1;
        $updateOrderInfo['status'] = 4;//状态为4[师傅修改订单状态]

        $updateStatusRes = $RepairOrder->where($orderMap)->save($updateOrderInfo);
        ////////////////////////新增支付协议start/////////////////////////////////
        //新增支付协议，将status设置为1[师傅修改]
        $RepairOrderProtocol = M('RepairOrderProtocol');
        $RepairOrderInfo = $RepairOrderProtocol->where(array('order_id' => $order_id, 'status' => 1, 'user_id' => $userInfo['worker_user_id']))->find();
        if (!empty($RepairOrderInfo)) {
            $return['err_code'] = 2011;
            $return['err_msg'] = '业主没确认修改订单，业主确认或者不同意后方可进行修改';
            $this->ajaxReturn($return, 'JSON');
        }
                  //维修金
        $protocolData = array();
        $protocolData['agreement_id'] = $agreement_id; //协议id
        $protocolData['gold'] = $data['itemCostTotal'];//金额

        if(!empty($fixed_price) && $fixed_price!=0.00){
            $protocolData['fixed_price'] = $fixed_price; //一口价
            $data['itemCostTotal'] = $fixed_price;
        }
        $bond = bcmul($data['itemCostTotal'], $agreementInfo['assure_percentage']/100, 3); //保证金
        $maintain = bcmul($data['itemCostTotal'], $agreementInfo['percentage']/100, 3);

        $protocolData['maintain'] = $maintain;//维修金
        $protocolData['gold_ratio'] = $agreementInfo['percentage'];// 维修金比例
        $protocolData['unit'] = $agreementInfo['unit'];// 单位
        $protocolData['count'] = $agreementInfo['count'];// 维保期[针对unit的单位]
        $protocolData['bond'] = $bond;//维修保证金
        $protocolData['bond_ratio'] = $agreementInfo['assure_percentage'];//维修保证金比例
        $protocolData['status'] = 1;//状态1:为师傅修改
        $protocolData['add_time'] = time();//添加时间
        $protocolData['months'] = $agreementInfo['count'];//维修保证金到账月数
        $protocolData['order_id'] = $order_id;//订单对内id
        $protocolData['user_id'] = $userInfo['user_id'];//用户id
        $protocolData['update_cnt'] = $updateOrderInfo['update_cnt'];//修改次数
        $RepairOrderProtocolAddRes = $RepairOrderProtocol->add($protocolData);
        ////////////////////////新增支付协议end/////////////////////////////////

        $returnData = array();
        $costAddCnt = count($costData);
        $costAddSuccessCnt = 0;

        //删除原有故障信息
        $RepairOrderDetail->where("repair_order_id = $userInfo[repair_order_id]")->delete();
        foreach ($costData as $key => $val) {
            $detailData = array();
            $detailData['fault_type'] = '1';//[故障类型:1标准,2非标准]
            $detailData['repair_order_id'] = $repair_order_id;//对内订单号
            $detailData['fault_id'] = $val['fault_id'];//对应故障id
            $detailData['price'] = $val['costTotal'];//对应故障金额
            $detailData['status'] = 1;//状态
            $detailData['add_time'] = time();//时间戳
            $detailData['material_cost'] = $val['material_cost'];//主材钱
            $detailData['deplete_cost'] = $val['deplete_cost'];//耗材钱
            $detailData['artificial_cost'] = $val['artificial_cost'];//人工费
            $detailData['fault_name'] = $val['name'];//故障名
            $detailData['update_cnt'] = $update_cnt + 1;//修改的次数
            $returnData[] = $detailData;
            $resultDetail = $RepairOrderDetail->add($detailData);//插入到订到描述表
            if ($resultDetail > 0) {
                $costAddSuccessCnt++;
            }
        }

        //设置师傅自定义故障类型
        $cost_fault_id['fault_id'] = array('eq','0');
        $cost_fault_type['fault_type'] = 3;

        $RepairOrderDetail->where($cost_fault_id)->save($cost_fault_type);

        //插入到订单记录表
        $RepairOrderStatusHistoryRes = $this->addToHistory($repair_order_id, 4, 0);
        $repairDetailStatus3Info = $RepairOrderDetail->where(array('status' => 3, 'repair_order_id' => $orderInfo['repair_order_id']))->find();
        $repairProtocolStatus3Info = $RepairOrderProtocol->where(array('status' => 3, 'order_id' => $order_id))->find();
        if (!empty($repairDetailStatus3Info)) {
            $status5 = $RepairOrderDetail->where(array('status' => 3, 'repair_order_id' => $orderInfo['repair_order_id']))->save(array('status' => 4));//将业主不同意的订单设置为
        } else {
            $status5 = 1;
        }
        if (!empty($repairProtocolStatus3Info)) {
            $status6 = $RepairOrderProtocol->where(array('status' => 3, 'order_id' =>$order_id ))->save(array('status' => 4));//将业主不同意的订单设置为
        } else {
            $status6 = 1;
        }
        if ($RepairOrderStatusHistoryRes > 0 && $updateStatusRes > 0 && $RepairOrderProtocolAddRes > 0 && $costAddSuccessCnt == $costAddCnt && $status5 > 0 && $status6 > 0) {
            //把以前的故障变为丢弃
            // $savve['status'] = 4;
            // $RepairOrderDetail->where(array('status' => 0, 'repair_order_id' => $orderInfo['repair_order_id']))->save($savve);
            $RepairOrder->commit();//所有成功就提交
        } else {
            $RepairOrder->rollback();//失败就回滚
            $return['err_code'] = 200;
            $return['err_msg'] = 'fault';
            $this->ajaxReturn($return, 'JSON');
        }

//        $orderInfo = $RepairOrder->find($repair_order_id);
//        $return['order_id'] = $orderInfo['repair_order_num_alias'];
//        $return['addr'] = $orderInfo['shipping_addr'];
//        $return['data'] = $returnData;

        $return['err_code'] = 200;
        $return['err_msg'] = 'success';
        $this->ajaxReturn($return, 'JSON');
        // // echo $order->test($insertMap);
    }


    /**
     *轮训订单是否有修改
     * @param phone string 电话号码
     * @param key string 密钥
     * @param rid string 当前登录用户的登录角色
     * @param order_id string 订单对外id
     */
    public function check_update_order()
    {
        $data = array();
        $data['code'] = 2013;
        $data['msg'] = '没有修改';
        $data['data'] = NULL;
        $data['category_name'] = '';
        $phone = I('post.phone', '', '/^1[3-9][0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/');//用户名
        $key = I('post.key', '', 'special_chars');//key
        $rid = I('post.rid/d', '');//当前登录用户的登录角色
        $order_id = I('post.order_id', '');//订单对外id
        $checkInfo = checkRole($phone, $key, $rid, false);//检测当前登录用户是否有操作权限
        if ($checkInfo['code'] != 200) {
            $this->ajaxReturn($checkInfo, 'JSON');
        }
        $user = M('user');
        $userMap = array();
        $userMap['phone'] = $phone;
        $RepairOrder = M('RepairOrder');
        $RepairOrderMap = array();
        $RepairOrderMap['repair_order_num_alias'] = $order_id;
        $orderInfo = $RepairOrder->where($RepairOrderMap)->find();
        if (empty($orderInfo)) {
            $return = array('code' => '2008', 'msg' => '不存在该订单');
            $this->ajaxReturn($return, 'JSON');
        }
        if ($orderInfo['user_id'] != $orderInfo['user_id']) {
            $return = array('code' => '2012', 'msg' => '您不是该订单的用户');
            $this->ajaxReturn($return, 'JSON');
        }
        $RepairOrderDetail = M('RepairOrderDetail');
        $RepairOrderProtocol = M('RepairOrderProtocol');
        $RepairOrderDetailMap = array();
        $RepairOrderDetailMap['status'] = 1;
        $RepairOrderDetailMap['repair_order_id'] = $orderInfo['repair_order_id'];
        $orderDetailInfo = $RepairOrderDetail->where($RepairOrderDetailMap)->select();
        $RepairOrderProtocolInfo = $RepairOrderProtocol
            ->field('unit,protocol_id,gold,maintain,gold_ratio,bond,bond_ratio,months')
            ->where(array(
                'status' => 1,
                'order_id' => $orderInfo['repair_order_id']
            ))->find();
        if (!empty($orderDetailInfo) || !empty($RepairOrderProtocolInfo)) {
            $data['msg'] = '有修改记录';
            $data['code'] = 200;
            $data['category_name'] = $orderInfo['category_name'];
            $data['data']['detail'] = $orderDetailInfo;
            $data['data']['protocol'] = $RepairOrderProtocolInfo;
        }
        $this->ajaxReturn($data, 'JSON');
    }

    /**
     * 下单页面[选择故障列表接口]
     * @param  string $user_name
     * @param  string $key
     * @param  string $rid 当前登录角色类型
     * @param  string $cid 当前选择的一级分类 多个以逗号方式隔开
     * @param int pagesize 每页显示的记录数
     * @param int currentPage 当前是第几页
     * @return array
     * @author lyz
     */
    public function getFaultList()
    {
        $phone = I('post.phone', '', 'special_chars');//用户名
//        $key = I('post.key', '', 'special_chars');//用户名
//        $rid = I('post.rid/d', '');//当前登录用户的登录角色
        $cid = I('post.cid', '');//当前登录用户选择的一级分类,
        $pagesize = I('post.pagesize/d', '');//每页显示的记录数
        $page = I('post.page/d', '');//当前是第几页
        $is_normal = I('post.is_normal/d', '');//是否返回全部数据 默认为返回全部数据 1为返回标准数据
//        $checkInfo = checkRole($phone, $key, $rid, false);//检测当前登录用户是否有操作权限
//        if ($checkInfo['code'] != 200) {
//            //   $this->ajaxReturn($checkInfo, 'JSON');
//        }
        $group = I('post.group', 0,'intval'); //用于html分组
        $dataInfo = array();//定义返回数据
        $dataInfo['err_code'] = 200;
        $dataInfo['isNextPage'] = false;
        $faultMap = array();
        $faultMap['category_id'] = array('in', $cid);//cid需要验证
        $faultMap['status'] = 1;//可用状态
        if ($is_normal > 0) {
            $faultMap['fault_type'] = 1;
        }
        $faultObj = M('fault');
        $faultList = $faultObj->field('fault_id,category_id,fault_type,name as fault_name,desc,order')->where($faultMap)->order(array('order' => 'desc'))->select();
        $faultCostObj = M('fault_cost');
        if (!empty($faultList)) {
            foreach ($faultList as $key => $val) {//查询故障对应的故障价格[顺风,标准,专修]
                $tmpFaultData = $faultCostObj->field('fault_id,type,material_cost,deplete_cost,artificial_cost')->where(array('fault_id' => $val['fault_id']))->select();
                foreach ($tmpFaultData as $kk => $vv) {
                    switch ($vv['type']) {
                        case 1:
                            $faultList[$key]['wind'] = $vv;//顺风价
                            break;
                        case 2:
                            $faultList[$key]['standard'] = $vv;//标准价
                            break;
                        case 3:
                            $faultList[$key]['expert'] = $vv;//专修价
                            break;
                    }
                    $faultList[$key]['expert']['fault_type'] = $val['fault_type'];
                    $faultList[$key]['wind']['fault_type'] = $val['fault_type'];
                    $faultList[$key]['standard']['fault_type'] = $val['fault_type'];
                }
            }
        }
//        $agreementWhere['category_id'] = $cid;
//        $agreement = M('agreement')->where($agreementWhere)->select();
        // var_dump($agreement);exit;
        if($group){
            $faultList and $faultList = array_chunk($faultList, 8);
        }
        $dataInfo['err_msg']= empty($faultList) ? array() : $faultList;
//        $dataInfo[err_msg]['agreement'] = $agreement;
        $dataInfo['cnt'] = count($faultList);
        $this->ajaxReturn($dataInfo, 'JSON');
    }

    /**
     * 获取附近的师傅
     * @param address_id 地址id
     * @param category_id 分类id
     * @param type 1距离 2星级 3成交数
     * @param distance 默认5KL
     */
    public function getNearbyMaster()
    {
        $address_id = I('post.address_id','');//地址id
        $addResult = M('address')->field('lng,lat,user_id')->where("id = $address_id")->find();

        $category_id = I('post.category_id'); //分类id
        $charging = I('post.charging/d', '');//计费方式(1顺风2标准3专修)
        $modeOrder = I('post.modeOrder/d', '');//订单类型（1即时订单2预约订单）
        if(!$category_id || !$charging || !$modeOrder || !$address_id){
            $return['code'] = '403';
            $return['msg'] = '参数缺失';
            $this->ajaxReturn($return, 'JSON');
        }
        $pageSize = I('post.pageSize/d', 10);//每页显示的记录数
        $pageIndex = I('post.pageIndex/d', 1);//当前是第几页
        $type = I('post.type','1'); //排序

//        //取用户经纬度
//        $userModel = M('user');
//        $userInfo = $userModel->field('user_id,lng,lat')->where(array('phone' => $phone))->find();
//        if (empty($userInfo)) {
//            //没有经纬度返回给前端设置用户经纬度
//            $return['code'] = '2017';
//            $return['msg'] = '失败，请先设置用户经纬度';
//            $this->ajaxReturn($return, 'JSON');
//        }
        $lat = $addResult['lat'];
        $lng = $addResult['lng'];
        $user_id = $addResult['user_id'];

        $orderObj = D('Order');
        $userList = $orderObj->getMasterList($user_id,$lng, $lat, $modeOrder, $charging, $category_id ,$pageSize ,$pageIndex , $type);
        $return['err_code'] = '200';
        $return['err_msg'] = $userList;
        $this->ajaxReturn($return, 'JSON');

    }

    /***
     * 比对传入故障数，与实际数据库故障数量 是否一致
     * @param $faultIds 故障id
     * @return array
     * @author lyz
     */
    private function checkFaultCnt($faultIds)
    {

        $faultObj = M('fault');
        $faultMap['fault_id'] = array('in', $faultIds);//故障id
        $faultMap['status'] = 1;//状态
        $fault_type = 1;
        $faultIdList = $faultObj->field('fault_id,fault_type')->where($faultMap)->select();
        foreach ($faultIdList as $key => $val) {
            if ($val['fault_type'] == 2) {
                $fault_type = 2;
            }
        }
        $faultCnt = count($faultIdList);
        $faultIdCnt = count(explode(',', $faultIds));
        if ($faultCnt != $faultIdCnt) {
            $errorInfo['code'] = '2004';
            $errorInfo['msg'] = '故障类型不对应';
            //$this->ajaxReturn($errorInfo, 'JSON');
            //故障类型不对应[传入个数，与实际数据库个数不一致]
        } else {
            $errorInfo['code'] = '200';
            $errorInfo['msg'] = '';
            $errorInfo['fault_type'] = $fault_type;
        }
        return $errorInfo;
    }

    /**传入故障类型的分类与传入分类是否对应
     * @param $cid  分类id
     * @param $faultids 故障id
     * @return
     */
    private function _checkCategory($cid, $faultids)
    {
        $flag = false;
        $faultArr = M('fault')->where(array('fault_id' => array('in', $faultids)))->field('name,category_id')->select();
        foreach ($faultArr as $key => $val) {
            if ($val['category_id'] != $cid) {
                $flag = true;
            }
        }
        if ($flag) {
            $errorInfo['code'] = '2005';
            $errorInfo['msg'] = '故障分类不对应';
            $this->ajaxReturn($errorInfo, 'JSON');
        }
    }

    public function getOrderMaster()
    {
        $phone = I('post.phone', '', 'special_chars');//用户名
        $key = I('post.key', '', 'special_chars');//用户名
        $rid = I('post.rid/d', '');//当前登录用户的登录角色
        $order_id = I('post.order_id', '');//订单号
        $checkInfo = checkRole($phone, $key, $rid, false);//检测当前登录用户是否有操作权限
        if ($checkInfo['code'] != 200) {
            $this->ajaxReturn($checkInfo, 'JSON');
        }
        //查找订单
        $return = array('code' => '2008', 'msg' => '不存在该订单');
        $user = M('user');
        $map['phone'] = I('post.phone', '');
        $userInfo = $user->where($map)->find();
        $order = M('RepairOrder');
        $workMap = array();
        $map['repair_order_num_alias'] = $order_id;
        $orderInfo = $order->where($map)->find();
        $trafficArr = array(1 => '公交', 2 => '步行', 3 => '自驾车');
        //1公交2步行3自驾车
        if (!empty($orderInfo)) {
            if ($orderInfo['user_id'] != $userInfo['user_id']) {
                $return = array('code' => '2009', 'msg' => '你不是该订单的创建者');
            } else {
                $workMap['user_id'] = $orderInfo['worker_user_id'];
                $workUserInfo = $user->where($workMap)->field('user_name,phone,lng,lat')->find();
                if (!empty($workUserInfo)) {
                    $UserMode = M('UserMode');
                    $userModeInfo = $UserMode->field('mode_traffic')->where(array('user_id' => $workMap['user_id']))->find();
                    $workUserInfo['traffic'] = $trafficArr[$userModeInfo['mode_traffic']];
                    //zsf_user_mode查找上门方式
                    $distance = getDistance($userInfo['lat'], $userInfo['lng'], $workUserInfo['lat'], $workUserInfo['lng']);
                    $workUserInfo['distance'] = $distance;
                    unset($workUserInfo['lng']);
                    unset($workUserInfo['lat']);
                    $return = array('code' => '200', 'msg' => '返回成功', 'data' => $workUserInfo);
                } else {
                    $return = array('code' => '2009', 'msg' => '没有师傅接单', 'data' => $workUserInfo);
                }
            }
        }
        $this->ajaxReturn($return, 'JSON');

    }

    /**
     * @param $master_phone 师傅号码
     * @param $master_id   师傅id
     * @param $modeOrder
     * @param $modeCharging
     * @return bool
     */
    private function checkMaster($master_phone, $master_id, $modeOrder, $modeCharging)
    {
        $user = M('user');
        $flag = false;
        $where = "phone=$master_phone and u.role=2 and m.mode_cate = 1 and FIND_IN_SET($modeOrder,m.mode_order) and u.is_real=1 and FIND_IN_SET($modeCharging,m.mode_charging) ";
        $Model = M('UserMode');
        $userInfo = $Model
            ->alias('m')
            ->field("user_name,user_face,phone,lng,lat,u.user_id")
            ->join('__USER__ u ON u.user_id = m.user_id')
            ->where($where)
            ->find();
        if (!empty($userInfo) && $userInfo['user_id'] == $master_id) {
            $flag = true;
        }
        return $flag;
    }


    /**
     * 查找对应的电子券
     */
    public function orderVolumeList()
    {
        $phone = I('post.phone', '', 'special_chars');//用户名
        $key = I('post.key', '', 'special_chars');//用户名
        $rid = I('post.rid/d', '');//当前登录用户的登录角色
        $cid = I('post.cid/d', '');//当前订单的分类id
        $totalPrice = I('post.totalPrice', '');//当前订单总价格
        $checkInfo = checkRole($phone, $key, $rid, false);//检测当前登录用户是否有操作权限
        $return = array();
        $return['code'] = 1002;
        $return['msg'] = '';
        if ($checkInfo['code'] != 200) {
            $this->ajaxReturn($checkInfo, 'JSON');
        }
        $user = M('user');
        $map['phone'] = $phone;
        $userInfo = $user->where($map)->find();
        if (empty($userInfo)) {//找不到用户
            $return['code'] = 1006;
            $return['msg'] = '用户不存在，请重新登录';
            $this->ajaxReturn($return, 'JSON');
        }
        if ($rid != 1 || $userInfo['identity'] != 1) {//登录角色或者角色参数不为业主
            $return['code'] = 1020;
            $return['msg'] = '当前登录角色不为业主，请重新切换角色进行操作';
            $this->ajaxReturn($return, 'JSON');
        }
        //查找对应的电子券
        $volume = M('VolumeList');
        $volumeMap = array();
        $volumeMap['user_id'] = $userInfo['user_id'];
        $volumeMap['status'] = 1;
        //start_time>=2016-4-27 and end_time <=2016-4-29
        $volumeMap['end_time'] = array('egt', time());
        $volumeList = $volume->where($volumeMap)->select();
        if (!empty($volumeList)) {
            foreach ($volumeList as $key => $val) {//不符合分类的删除
                $categoryArr = explode('|', $val['category_id']);
                $volumeList[$key]['deadline'] = date('m-d',$volumeList[$key]['start_time']).' - '.date('m-d',$volumeList[$key]['end_time']);
                if (!in_array($cid, $categoryArr) || $volumeList[$key]['min']>$totalPrice) {
                    $volumeList[$key]['use'] = 'false';
                }else{
                    $volumeList[$key]['use'] = 'yes';
                }
            }
        } else {
            $volumeList = array();
        }
        sort($volumeList);
        $return['cnt'] = count($volumeList);
        $return['code'] = 200;
        $return['msg'] = '成功';
        $return['data'] = $volumeList;
        $this->ajaxReturn($return, 'JSON');
    }





    private function addToHistory($result, $status, $count = 0)
    {
        $OrderStatusHistory = M('OrderStatusHistory');
        $historyData = array();
        $historyData['order_id'] = $result;
        $historyData['status'] = $status;
        $historyData['order_type'] = 1;
        $historyData['add_time'] = time();
        $historyData['count'] = $count;
        $res = $OrderStatusHistory->add($historyData);
        return $res;
    }


    /**
     * 添加小费
     */
    public function addtip(){
        $order_id=I('post.id');
        $user_id=I('post.user_id','','int');
        $tip=I('post.tip');

        if(empty($tip)){
            $return['err_code'] = 2017;
            $return['err_msg'] = '小费不能为空';
            $this->ajaxReturn($return, 'JSON');
        }

        if(empty($order_id)){
            $return['err_code'] = 2017;
            $return['err_msg'] = '订单不能为空';
            $this->ajaxReturn($return, 'JSON');
        }

        if(empty($user_id)){
            $return['err_code'] = 2017;
            $return['err_msg'] = '用户不能为空';
            $this->ajaxReturn($return, 'JSON');
        }

        $where['repair_order_num_alias']=$order_id;

        $order=M('repair_order')->where($where)->find();

        if(!empty($order) && $order['status']==1 && $order['user_id']==$user_id){
                $sa['tip']=$tip;
                M('repair_order')->where($where)->save($sa);

                $statusHistory['order_id'] = array('eq',$order['repair_order_id']);
                $statusHistory['status'] = array('eq',1);
                $statusHistorySave['add_time'] = time();
                M('order_status_history')->where($statusHistory)->save($statusHistorySave);

                $return['err_code'] = 200;
                $return['err_msg'] = '成功';
                $this->ajaxReturn($return, 'JSON');
        }
            $return['err_code'] = 2016;
            $return['err_msg'] = '当前订单状态不能添加小费';
            $this->ajaxReturn($return, 'JSON');

    }

    /**
     * 转单顺风/专修
     * @param user_id 用户id
     * @param order_id 对外订单id
     * @type 1顺风 2标准 3专修
     */
    public function transformType(){
        $user_id = I('post.user_id');
        $data = self::checkUserIsExist($user_id);
        if(!$data['user']){
            $this->ajaxReturn($data);
        }
        $order_id = I('post.order_id');
        $type = I('post.type/d');

        $orderExist = M('repair_order')->field('repair_order_id,category_id,fault_id_list,mode_charging,diagnosis_cost')
                      ->where("repair_order_num_alias = $order_id and status = 1 and user_id = $user_id")
                      ->find();
        $model = M();
        $model->startTrans();
        if($orderExist){
            switch($type){
                case 1;
                    $dia = 'dia_wind_cost';break;
                case 2;
                    $dia = 'dia_standard_cost';break;
                case 3;
                    $dia ='dia_expert_cost';break;
            }
            $maps["repair_order_id"] = $orderExist['repair_order_id'];
            $newDia = M('category')->field("$dia")->where("category_id = $orderExist[category_id]")->find();
            if($newDia){
                //诊断费金额
                $maps['diagnosis_cost'] = $newDia[$dia];
                //故障金额
                $FaultCost['fault_id'] = array('in',$orderExist['fault_id_list']);
                $FaultCost['type'] = array('eq',$type);
                $FaultResult = M('fault_cost')->where($FaultCost)->select();
                $FaultTotal ='';
                //更新故障详情表
                $detailWhere['repair_order_id'] = $orderExist['repair_order_id'];
                foreach($FaultResult as $k=>$v){
                    $detailPrice ='';
                    $detailPrice = bcadd($detailPrice,$v['material_cost'],2);
                    $detailPrice = bcadd($detailPrice,$v['deplete_cost'],2);
                    $detailPrice = bcadd($detailPrice,$v['artificial_cost'],2);

                    $detailWhere['fault_id'] = array('eq',$v['fault_id']);
                    $detail['material_cost'] = $v['material_cost'];
                    $detail['deplete_cost'] = $v['deplete_cost'];
                    $detail['artificial_cost'] = $v['artificial_cost'];
                    $detail['price'] = $detailPrice;
                    //可能出现价格一样
                    $detailResult = M('repair_order_detail')->where($detailWhere)->save($detail);

                    $FaultTotal = bcadd($FaultTotal,$v['material_cost'],2);
                    $FaultTotal = bcadd($FaultTotal,$v['deplete_cost'],2);
                    $FaultTotal = bcadd($FaultTotal,$v['artificial_cost'],2);
                }
                $Total = bcadd($FaultTotal,$newDia[$dia],2);
                $maps['mode_charging'] = $type;
                $maps['total'] = $Total;
                $orderResult = M('repair_order')->save($maps);
                if($orderResult){
                    $model->commit();
                    $statusHistory['order_id'] = array('eq',$orderExist['repair_order_id']);
                    $statusHistory['status'] = array('eq',1);
                    $statusHistorySave['add_time'] = time();
                    M('order_status_history')->where($statusHistory)->save($statusHistorySave);

                    $array = array('err_code'=>200,'err_msg'=>'转单成功');
                    $this->ajaxReturn($array);
                }else{
                    $model->rollback();
                    $array = array('err_code'=>404,'err_msg'=>'转单失败');
                    $this->ajaxReturn($array);
                }
            }

        }else{
            $array = array('err_code'=>403,'err_msg'=>'订单不存在');
            $this->ajaxReturn($array);
        }

    }


    private function _getResult($orderId)
    {
        //$orderId=I('post.orderId');
       $redis = S(array('type' => 'redis'));

        //得到装修orderid
    //    $orderId = $redis->lpop(C('REPAIR_ORDER_PUSH_KEY'));
        /*
                if(!$orderId){
                    echo "111\n" ;
                    return;
                }*/
        // $orderId=168;`
        $orderMap = array();
        $RepairOrder = M('RepairOrder');
        $orderMap['repair_order_id'] = $orderId;
        $orderMap['status'] = 1;//待服务
        $orderData = $RepairOrder->where($orderMap)->find();
        if (empty($orderData)) {
            $RepairOrder->query("select now()");
            file_put_contents("/tmp/log.txt",var_export($orderData,true)."cant find order----".var_export($orderMap,true),FILE_APPEND);
            return;
            //订单不存在
        }

        $mode_charging = (int)$orderData['mode_charging'];
        $category_id = (int)$orderData['category_id'];
        //$fault_type=$orderData['fault_type'];
        $user_id = $orderData['user_id'];
        $user = M('user');
        $lng=$orderData['lng'];
        $lat=$orderData['lat'];
        //下订单的用户，距离师傅多少米
        $juli = "ROUND(6378.138*2*ASIN(SQRT(POW(SIN(({$lat}*PI()/180-lat*PI()/180)/2),2)+COS({$lat}*PI()/180)*COS(lat*PI()/180)*POW(SIN(({$lng}*PI()/180-lng*PI()/180)/2),2)))*1000) AS juli";
        $order_type = $orderData['order_type'];
        $UserMode = M('UserMode');
        $prex = C('DB_PREFIX');
//        $sql = " LEFT JOIN {$prex}user on {$prex}user.user_id={$prex}user_mode.user_id ";
//        $sql .= " where  {$prex}user.is_listen=1 and {$prex}user.role=2 ";
//        $sql .= " and {$prex}user_mode.mode_cate =1 and FIND_IN_SET('$order_type',{$prex}user_mode.mode_order) ";
//        $sql .= " and {$prex}user.is_real=1";
//        $sql .= " and FIND_IN_SET('$mode_charging',{$prex}user_mode.mode_charging) ";
        ///////测试
        $sql = " LEFT JOIN {$prex}user on {$prex}user.user_id={$prex}user_mode.user_id ";
        $sql .= " LEFT JOIN {$prex}user_repair_conf on {$prex}user_repair_conf.user_id={$prex}user.user_id ";
        //$sql .= " where  {$prex}user.is_listen=1 and {$prex}user.role=2 and ";
        $sql .= " where  {$prex}user.role=2 and ";
        $sql .= "FIND_IN_SET($order_type,{$prex}user_mode.mode_order) ";
     //   $sql .= "  {$prex}user.is_real=1";
        $sql .= " and {$prex}user.is_real=1";
        $sql .= " and {$prex}user_repair_conf.category_id=$category_id";
        $sql .= " and {$prex}user.user_id!={$orderData['user_id']}";
        $sql .= " and FIND_IN_SET($mode_charging,{$prex}user_mode.mode_charging) ";
        file_put_contents("/tmp/sql.txt",$sql."----",FILE_APPEND);
        $masterList = $UserMode
            ->field("DISTINCT {$prex}user.user_id,{$prex}user.push_name,{$prex}user.phone,{$prex}user.is_real,$juli")
            ->join(array($sql))
            ->order('juli asc')
            ->select();

        file_put_contents("/tmp/sql.txt",$UserMode->getLastSql()."----",FILE_APPEND);
        //jpush
        $pushData = array();//推送信息
        $pushData['shippingAddr'] = $orderData['shipping_addr'];
        $pushData['bookTime'] = $orderData['book_time'];
        $pushData['categoryName'] = M('category')->field('category_name')->find($orderData['category_id']);
        $pushData['faultList'] = $this->_getFailNames($orderData['fault_id_list']);
        /*category_id
        fault_type //1是标准[给出总价],2是非标准[只给出诊断费不给出总价]*/
        if ($orderData['fault_type'] == 1) {
            $pushData['price'] = $orderData['total'];
        } else {
            $pushData['diagnosis_cost'] = $orderData['diagnosis_cost'];
        }
        // $jpushObj = new \Org\Util\JPush_test();
        $pushCnt = 0;
        $pushorderModel = M('Pushorder');
        file_put_contents("/tmp/sql.txt",$masterList."----",FILE_APPEND);
        foreach ($masterList as $key => $val) {
            //要分别推送
            //写入到zsf_repair_order_push
            $map['user_id'] = $val['user_id'];
            $map['order_id'] = $orderId;
            $pushorderData=$pushorderModel->where($map)->find();
            //$pushorderData = $pushorderModel->data();
            //var_dump($pushorderData);exit;
            if (empty($pushorderData)) {
                $this->_add2PushOrder($pushorderModel, $val['user_id'], $orderId);
            }
            /*  $receive = 'all';//别名
              $content = '那个傻逼？';
              $m_type = 'tb';
              $m_txt = json_encode($pushData);
              $m_time = '600';        //离线保留时间
              $res = $jpushObj->send_pub($receive, 111, '', $m_txt, $m_time);*/
            // var_dump($res);
            if (!empty($res)) {
                $pushCnt++;
            }
        }
        $redis->lpush(C('REPAIR_ORDER') . '_' . $orderId, $masterList);//对应的抢单师傅列表
        file_put_contents("/tmp/log.txt","pushdata====".var_export(C('REPAIR_ORDER') . '_' . $orderId,true)."\r\n",FILE_APPEND);
        $pushRes=$redis->set(C('REPAIR_ORDER') . '_key_' . $orderId, 1);//抢单数量设置成1
        $redis->expire(C('REPAIR_ORDER') . '_key_' . $orderId,86400);
        //$pushRes=S(C('REPAIR_ORDER') . '_key_' . $orderId,1);
        file_put_contents("/tmp/log.txt","pushdata====".var_export($pushRes,true)."\r\n",FILE_APPEND);
        if ($pushCnt > 0) {
            $data['repair_order_id'] = $orderId;
            $data['push_cnt'] = $pushCnt;
            $res = $RepairOrder->save($data);
        }
        //REPAIR_ORDER
        //修改订单表中的推送了多少个师傅字段
        //往redis里面插入一条订单记录
        //指派下单的话，只推送给指定的师傅
        //不是指派下单，则取查找
        //查找模式设置里面的分类为装修的
        //查找模式设置里面的订单类型为对应的下单类型的
    }

    private function _add2PushOrder($model, $user_id, $order_id)
    {
        $model->user_id = $user_id;
        $model->order_id = $order_id;
        $model->status = 0;
        $flag=$model->add();
        file_put_contents("/tmp/sql.txt",$user_id."--addMaster--".$flag."----",FILE_APPEND);

    }

    /**
     * 查找故障列表对应的名字
     * @params $fids string 故障列表[id]
     */
    private function _getFailNames($fids)
    {
        $faultNameStr = '';
        $faultArr = M('fault')->where(array('fault_id' => array('in', $fids)))->field('name')->select();
        if (!empty($faultArr)) {
            foreach ($faultArr as $key => $val) {
                $faultNameStr .= ',' . $val['name'];
            }
            $faultNameStr = ltrim($faultNameStr, ',');
        }
        return $faultNameStr;
    }
}